package com.me.uniplugin;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.IBinder;

import java.io.File;
import java.io.IOException;

public class RecordService extends Service {
    private int ratio;
    private int frame;
    private boolean isAudio;

    private int mScreenWidth;
    private int mScreenHeight;
    private int mScreenDensity;
    private int mResultCode;

    private String recordPath;

    private Intent mResultData;

    private MediaProjection mMediaProjection;
    private MediaRecorder mMediaRecorder;
    private VirtualDisplay mVirtualDisplay;

    public RecordService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * 开始录制
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        ratio = intent.getIntExtra("ratio", 3);
        frame = intent.getIntExtra("frame", 30);
        isAudio = intent.getBooleanExtra("isAudio", false);

        mResultCode = intent.getIntExtra("resultCode", 1);
        recordPath = intent.getStringExtra("recordPath");
        mResultData = intent.getParcelableExtra("data");

        getScreenBaseInfo();

        mMediaProjection = createMediaProjection();
        mMediaRecorder = createMediaRecorder();
        mVirtualDisplay = createVirtualDisplay(); // 必须在mediaRecorder.prepare() 之后调用，否则报错"fail to get surface"

        mMediaRecorder.start();
        return Service.START_NOT_STICKY;
    }

    /**
     * 结束录制
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mVirtualDisplay != null) {
            mVirtualDisplay.release();
            mVirtualDisplay = null;
        }
        if(mMediaRecorder != null) {
            mMediaRecorder.setOnErrorListener(null);
            mMediaProjection.stop();
            mMediaRecorder.reset();
        }
        if(mMediaProjection != null) {
            mMediaProjection.stop();
            mMediaProjection = null;
        }
        // 保存到相册
        File file = new File(recordPath);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(file));
        sendBroadcast(intent);
    }


    /**
     * 获取屏幕相关数据
     */
    private void getScreenBaseInfo() {
        mScreenWidth = ScreenUtils.getScreenWidth(this);
        mScreenHeight = ScreenUtils.getScreenHeight(this);
        mScreenDensity = ScreenUtils.getScreenDensityDpi(this);
    }

    private MediaProjection createMediaProjection() {
        return ((MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE)).getMediaProjection(mResultCode, mResultData);
    }


    private MediaRecorder createMediaRecorder() {
        MediaRecorder mediaRecorder = new MediaRecorder();
        if(isAudio){ // 录制声音
            mediaRecorder.setAudioChannels(1); // 1单声道，2双声道
            mediaRecorder.setAudioSamplingRate(44100); // 采样频率: 8kHz、11.025kHz、22.05kHz、16kHz、37.8kHz、44.1kHz、48kHz、96kHz、192kHz
            mediaRecorder.setAudioEncodingBitRate(96000); // 码率: 低32kbps-96kbps, 高96kbps-192kbps
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); // 麦克风MIC, 语音识别VOICE_RECOGNITION, 语音通话VOICE_COMMUNICATION
        }

        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mediaRecorder.setOutputFile(recordPath);
        mediaRecorder.setVideoSize(mScreenWidth, mScreenHeight);  //after setVideoSource(), setOutFormat() 1080*2356
        mediaRecorder.setVideoEncodingBitRate(ratio * mScreenWidth * mScreenHeight); // 清晰度, 建议取值: 1,2,3,4,5,6; 越大越清晰, 默认3 (值越大内存要求越高, 太高容易内存溢出闪退)
        mediaRecorder.setVideoFrameRate(frame); // 视频帧率, 建议取值: 15,20,25,30,60; 越大越流畅, 默认30
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);  //after setOutputFormat()
        if(isAudio) mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);  //after setOutputFormat()

        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }

        return mediaRecorder;
    }

    private VirtualDisplay createVirtualDisplay() {
        return mMediaProjection.createVirtualDisplay("createVirtualDisplay", mScreenWidth, mScreenHeight, mScreenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mMediaRecorder.getSurface(), null, null);
    }

}